new Vue({
    el: '#app',
    data: {
        cartItems: [],
        sum: 0,
        isSelectAll: false, // 全选状态
        userAvatarUrl: '', // 用户头像URL
        username: '' // 用户名
    },
    computed: {
        totalAmount() {
            // 计算选中商品的总金额，从 commodityList 中过滤和计算
            if (!this.cartItems || !this.cartItems.commodityList) {
                return '0.00';
            }
            // 计算选中商品的总金额
            return this.cartItems.commodityList
                .filter(item => item.selected)
                .reduce((sum, item) => sum + item.commoditySalePrice * item.commodityNum, 0)
                .toFixed(2);
        },
        // 计算属性，判断是否所有商品都被选中
        isAllSelected() {
            if (!this.cartItems || !this.cartItems.commodityList || this.cartItems.commodityList.length === 0) {
                return false;
            }
            return this.cartItems.commodityList.every(item => item.selected);
        }
    },

    methods: {
        // 从服务器端获取购物车商品列表
        fetchCart() {
            $.ajax({
                url: 'http://localhost:8080/cart/findCommodityByUserId',
                type: 'GET',
                data: { userId: localStorage.getItem('userId')},
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    console.log(res);
                    if (res.code === 200) {
                        this.cartItems = res.data;
                        // this.cartItems.commodityList.forEach(item => {
                        //     item.image = '\\' + item.commodityPicture[0].commodityImageUrl.match(/photo[\\\\/].+$/)[0];
                        // })
                        // this.cartItems.commodityList.map(item => ({
                        //     ...item,
                        //     selected: false
                        // }));
                        // 使用 $set 确保 selected 是响应式的
                        this.cartItems.commodityList = res.data.commodityList.map((item, index) => {
                            this.$set(item, 'selected', false); // 强制设置响应式字段
                            item.image = 'http://localhost:8080' + item.commodityPicture[0].commodityImageUrl;

                            // 清理 spec 数据，去掉可能存在的前导冒号
                            if (item.spec1 && typeof item.spec1 === 'string' && item.spec1.startsWith(':')) {
                                item.spec1 = item.spec1.substring(1);
                            }
                            if (item.spec2 && typeof item.spec2 === 'string' && item.spec2.startsWith(':')) {
                                item.spec2 = item.spec2.substring(1);
                            }
                            return item;
                        });
                        // this.sum = this.cartItems.commodityList.reduce((sum, item) => sum + item.commoditySalePrice * item.commodityNum, 0).toFixed(2);
                        // 初始化总金额
                        this.updateTotalAmount();

                    } else {
                        this.cartItems = [];
                    }
                },
                error: () => {
                    this.cartItems = [];
                }
            });
        },
        getSpecArray(specProduct) {
            if (!specProduct) return [];
            // 去除首尾空格，按逗号分割，过滤空项
            return specProduct.split(',').map(s => s.trim()).filter(s => s);
        },
        // 更新总金额
        updateTotalAmount() {
            this.sum = this.totalAmount;
        },
        // 增加商品数量
        increaseQuantity(item) {
            $.ajax({
                url: 'http://localhost:8080/cart/updateCommodityNum',
                type: 'GET',
                data: { orderId: this.cartItems.orderId, productId: item.commodityId, quantity: item.commodityNum + 1 },
                contentType: 'application/json',
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        item.commodityNum++; // 更新本地数量
                        this.sum = parseFloat(this.sum) + parseFloat(item.commoditySalePrice);
                        this.sum = this.sum.toFixed(2);

                    }
                }
            });
        },
        // 减少商品数量
        decreaseQuantity(item) {
            if (item.commodityNum <= 1) return;
            $.ajax({
                url: 'http://localhost:8080/cart/updateCommodityNum',
                type: 'GET',
                data: { orderId: this.cartItems.orderId, productId: item.commodityId, quantity: item.commodityNum - 1 },
                contentType: 'application/json',
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        item.commodityNum--;
                        this.sum = this.sum - parseFloat(item.commoditySalePrice);
                        this.sum = this.sum.toFixed(2);
                    }
                }
            });
        },
        // 从购物车中移除商品
        removeItem(productId) {
            $.ajax({
                url: 'http://localhost:8080/cart/deleteCommodityFromCart',
                type: 'POST',
                data: { orderId: this.cartItems.orderId, productId: productId },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        this.cartItems.commodityList = this.cartItems.commodityList.filter(item => item.commodityId !== productId);
                    }
                }
            });
        },
        // 结算功能：将购物车商品信息发送到后台并跳转到订单确认页
        checkout() {
            // 获取选中的商品
            const selectedItems = this.cartItems.commodityList.filter(item => item.selected);

            if (selectedItems.length === 0) {
                alert('请至少选择一件商品进行结算。');
                return;
            }

            // 准备要发送到后台的数据
            console.log('selectedItems:', selectedItems);

            const commodityMap = selectedItems.reduce((acc, item) => {
                acc[item.commodityId] = { // 将 commodityId 作为键
                    commodityNum: item.commodityNum, // 数量
                    spec1: item.spec1,           // 规格1
                    spec2: item.spec2            // 规格2
                };
                return acc;
            }, {});


            // 发送AJAX请求到后台，保存购物车信息并获取订单标识符
            $.ajax({
                url: 'http://localhost:8080/cart/buyCommodity?userId=' + localStorage.getItem('userId'),
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(commodityMap),
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200 && res.data) {
                        window.location.href = `order-confirm-test.html?orderId=${res.data}`;
                    } else {
                        alert('订单准备失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，订单准备失败。');
                    console.error('AJAX error preparing order:', status, error);
                }
            });
        }
    },
    watch: {
        // 监听isSelectAll的变化来更新所有商品的选中状态
        isSelectAll(newVal) {
            // this.cartItems.commodityList.forEach(item => {
            //     item.selected = newVal;
            // });
            this.cartItems.commodityList.forEach((item, index) => {
                this.$set(this.cartItems.commodityList[index], 'selected', newVal);
            });
        },
        // 监听cartItems中每个商品的selected状态变化来更新isSelectAll和总金额
        'cartItems.commodityList': {
            handler() {
                this.isSelectAll = this.isAllSelected;
                this.updateTotalAmount(); // 更新总金额
            },
            deep: true
        }
    },
    created() {
        this.fetchCart();
    }
}); 